package com.scau.hwadee.examination.utils;

/**
 * @author: YHX
 * @Date: 2019/7/19 19:59
 */

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.util.List;

/**
 * JSON序列化和反序列化的工具
 */
@Slf4j
public class JsonUtils {

  public static String ObjectToJSON(Object object) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      String s = objectMapper.writeValueAsString(object);
      log.debug("对象转JSON字符串成功");
      return s;
    } catch (Exception e) {
      log.debug("对象转JSON字符串失败,错误为：", e);
      return null;
    }
  }

  /**
   * JSON字符串转对象
   *
   * @param jsonString
   * @param beanType
   * @param <T>
   * @return
   */
  public static <T> T JSONToObject(String jsonString, Class<T> beanType) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      T t = objectMapper.readValue(jsonString, beanType);
      log.debug("JSON字符串转对象成功");
      return t;
    } catch (Exception e) {
      log.debug("JSON字符串转对象失败：", e);
      return null;
    }
  }

  /**
   * @param jsonString
   * @param beanType
   * @param format
   * @return T
   * @author YHX
   * @description JSON字符串转对象 加上时间参数
   * @date 10:49 2019/8/7
   **/
  public static <T> T JSONToObject(String jsonString, Class<T> beanType, DateFormat format) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      objectMapper.setDateFormat(format);
      T t = objectMapper.readValue(jsonString, beanType);
      log.debug("JSON字符串转对象成功");
      return t;
    } catch (Exception e) {
      log.debug("JSON字符串转对象失败：", e);
      return null;
    }
  }


  /**
   * @param jsonString json字符串
   * @param beanType   类的类型
   * @return java.util.List<T>
   * @author YHX
   * @description JSON字符串转对象List
   * @date 10:48 2019/8/7
   **/
  public static <T> List<T> JSONToList(String jsonString, Class<T> beanType) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      JavaType javaType = objectMapper.getTypeFactory().constructType(beanType);
      List<T> list = objectMapper.readValue(jsonString, javaType);
      log.debug("JSON字符串转List成功");
      return list;
    } catch (Exception e) {
      log.debug("JSON字符串转List失败", e);
      return null;
    }
  }


}
